﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// Window2.xaml 的交互逻辑
    /// </summary>
    public partial class Window2 : Window
    {
        public SerialPort serialPort;//串口对象类
        public Window2()
        {
            InitializeComponent();
            if (InitCOM("COM4"))
            {
                SendCommand("asdasdasd");//发送字符
            }
        }
        /// 串口接收通信配置方法
        /// 端口名称
        public bool InitCOM(string PortName)
        {
            serialPort = new SerialPort(PortName, 115200, Parity.None, 8, StopBits.One);

            serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);//DataReceived事件委托
            serialPort.ReceivedBytesThreshold = 1;
            serialPort.RtsEnable = true;
            return OpenPort();//串口打开
        }
        /// 数据接收事件
        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(500);
            //byte[] readBuffer = new byte[serialPort.ReadBufferSize];
            //serialPort.Read(readBuffer, 0, readBuffer.Length);
            var s = serialPort.ReadExisting();
            Console.WriteLine(s);
            //string str = System.Text.Encoding.Default.GetString(readBuffer);

            //string[] arr = str.Split('\r');
 
            //Console.WriteLine(arr[0]);
            //MessageBox.Show(str);
        }
        //打开串口的方法
        public bool OpenPort()
        {
            try//这里写成异常处理的形式以免串口打不开程序崩溃
            {
                serialPort.Open();
            }
            catch { }
            if (serialPort.IsOpen)
            {
                return true;
            }
            else
            {
                MessageBox.Show("串口打开失败!");
                return false;
            }
        }
        //向串口发送数据
        public void SendCommand(string CommandString)
        {
            byte[] WriteBuffer = Encoding.ASCII.GetBytes(CommandString);
            serialPort.Write(WriteBuffer, 0, WriteBuffer.Length);
        }
    }
}
